package com.baizhiedu.basic;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * ClassName: BeanFactory
 * Description:
 * Date: 2022/11/18 PM 2:46:39
 * <p>
 * project: spring5
 * package: org.baizhiedu.basic
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class BeanFactory {

    private static final Properties env = new Properties();

    static {
        InputStream inputStream = null;
        // 第一步 获得 IO 输入流
        try {
            inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
            // 第二部 文件内容 封装 Properties 集合中 key = userService value = com.baizhiedu.xxx.UserServiceImpl
            env.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }

    /**
     * 对象的创建方式
     * 1.直接调用构造方法，创建对象  UserService userService = new UserServiceImpl();
     * 2.通过反射的形式创建对象 解耦合
     * Class clazz = Class.forName("com.baizhiedu.basic.UserServiceImpl");
     * UserService userService = (UserService)clazz.newInstance();
     *
     * @return userService
     */
    /*public static UserService getUserService() {
        UserService userService = null;
        try {
            Class<?> clazz = Class.forName(env.getProperty("userService"));
            userService = (UserService) clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return userService;
    }

    public static UserDao getUserDao() {
        UserDao userDao = null;
        try {
            Class<?> clazz = Class.forName(env.getProperty("userDao"));
            userDao = ((UserDao) clazz.newInstance());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return userDao;
    }*/

    /**
     * key 小配置文件中的 key [userDao, userService]
     *
     * @param key key
     * @return 对象
     */
    public static Object getBean(String key) {
        Object ret = null;
        try {
            Class<?> clazz = Class.forName(env.getProperty(key));
            ret = clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }
}
